package Solution.problem082.RemoveDuplicatesFromSortedList2;

import common.ListNode;
import org.junit.Test;

/**
 * @program Leetcode
 * @description:
 * @author: lishangsheng
 * @create: 2019/06/15 16:39
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        //建立假节点指向表头
        head = dummy;
        //建立指针从假节点遍历，这里用head作为指针节省一点儿空间
        while (head.next != null && head.next.next != null) {
            //特殊情况处理，即空链表和单节点的链表
            if (head.next.val == head.next.next.val) {
                //找到后继中第一个不重复的节点
                int val = head.next.val;
                //记录一下后继的值，便于后面搜索
                while(head.next != null && head.next.val == val)
                    head.next = head.next.next;
                //只改变后继的next域，这样做可以保证前驱一直指向重复节点的头，因此找到节点后使驱现在指向第一个不重复的节点，相当于跨过所有重复的节点
            }
            else
                head = head.next;
            //将指针移动到找到的第一个不重复的节点
        }
        return dummy.next;
        //返回
    }



    private void getNextNode(ListNode temp, int value) {
        while (temp.next != null) {
            if (temp.next.val == value) {
                temp = temp.next;
            }else {
                break;
            }
        }
    }

    @Test
    public void test() {
        //1->2->3->4->5
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(1);
        ListNode listNode3 = new ListNode(1);
        ListNode listNode4 = new ListNode(3);
        ListNode listNode5 = new ListNode(4);
        ListNode listNode6 = new ListNode(4);
        ListNode listNode7 = new ListNode(5);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        listNode4.next = listNode5;
        listNode5.next = listNode6;
        listNode6.next = listNode7;
        ListNode result = deleteDuplicates(listNode1);
        System.out.println(result.val);
    }
}


